package org.trinity.netdisk.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.trinity.netdisk.enums.ResultCode;
import org.trinity.netdisk.util.JWTUtil;
import org.trinity.netdisk.util.ResponseWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println(request.getRequestURI());
        if (JWTUtil.verify(token) || "OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        ResponseWrapper responseWrapper = new ResponseWrapper(ResultCode.NO_PERMISSION);
        String responseJSON = new ObjectMapper().writeValueAsString(responseWrapper);

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(responseJSON);

        return false;
    }
}
